const btn = document.querySelector('.myBtn')
const rBtn = document.querySelector('.regBtn')
const form = document.querySelector("form")
const myToast = new bootstrap.Toast('.toast')
const toastBody = document.querySelector('.toast-body')

rBtn.addEventListener('click', (e) => {
	e.preventDefault()
	location.href = './index.html'
})

btn.addEventListener('click', async e => {
	e.preventDefault()
	const data = serialize(form, {hash: true, empty: true})
	const {username, password} = data
	if (username.length < 2 || username.length > 30) {
		myToast.show()
		toastBody.innerHTML = "用户名不对哈"
		return;
	}
	if (password.length < 6 || password.length > 30) {
		myToast.show()
		toastBody.innerHTML = "密码不对哈"
		return;
	}
	try {
		const res = await axios({
			url: '/login',
			method: 'post',
			data,
		})
		toastBody.innerHTML = res.data.message
		setTimeout(() => {
			location.href = './interface.html'
		}, 2000);
		localStorage.setItem('token',res.data.data.token)
		localStorage.setItem('username',res.data.data.username)
	} catch (e) {
		console.dir(e)
		toastBody.innerHTML = e.response.data.message
	}
	myToast.show()
})
